<?php

namespace App\Console\Commands\Feishu\Nsq;


use App\Enums\Common\NsqEnum;
use App\Library\FeiShu\SendFs;
use App\Models\Common\ConfigModel;
use App\Service\OpenShop\Feishu\MessageSendService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Kuafu\GeneralFs\BuildFs;
use Kuafu\Nsq\NsqSubscriber;
use NSQClient\Contract\Message;

class NsqSubFsRobotCommand extends Command
{
    protected $signature = 'nsq:sub-fs-robot';

    protected $description = 'NSQ订阅飞书机器人发送';

    private array  $data;
    private string $module;
    private string $projectName;
    private        $robotValue;
    private array  $body;
    private string $feishuId;

    /**
     * 自定义webhock机器人配置
     * @var array|string[]
     */
    private array $robotConfig = [
        'url'   => '',
        'token' => '',
    ];

    public function handle()
    {
        (new NsqSubscriber(config('nsq.default.address')))
            ->sub(NsqEnum::TOPIC_TIGER_FS_ROBOT_SEND, NsqEnum::CHANNEL_TIGER_SUB_FS_ROBOT_SEND,
                function (Message $message) {

                    // debug
                    if (isTest()) {
                        dump($message->data());
                    }

                    $this->data = $message->data();

                    try {
                        $this->doHandle();
                    } catch (\Exception $e) {
                        \ExceptionNotifier::report($e);
                    }

                    $message->done();
                });
    }

    private function doHandle()
    {
        $module      = $this->data['module'] ?? BuildFs::MODULE_TYPE_WEBHOCK;
        $projectName = $this->data['projectName'] ?? '';
        $robotValue  = $this->data['robotValue'] ?? null;
        $body        = $this->data['fsBody'] ?? [];
        $feishuId    = $this->data['feishuId'] ?? '';
        $robotConfig = $this->data['robotConfig'] ?? [];

        Log::channel('fsRobot')->info("NsqSubFsRobotCommand Start", $this->data);

        if (!$projectName || !$body || !$module) {
            return;
        }

        if ($robotValue === null && !$robotConfig && !is_array($robotConfig)) {
            return;
        }

        if ($module == BuildFs::MODULE_TYPE_APP && !$feishuId) {
            return;
        }

        $this->module      = $module;
        $this->projectName = $projectName;
        $this->robotValue  = $robotValue;
        $this->body        = $body;
        $this->feishuId    = $feishuId;
        $this->robotConfig = $robotConfig;

        switch ($this->module) {
            case BuildFs::MODULE_TYPE_WEBHOCK:
                $this->webhock();
                break;
            case BuildFs::MODULE_TYPE_APP:
                $this->app();
                break;
        }
    }

    /**
     * webhock机器人推送
     * @return void
     */
    private function webhock(): void
    {
        if ($this->robotConfig) {
            $url = $this->robotConfig['url'] ?? '';
            $token = $this->robotConfig['token'] ?? '';
        } else {

            // 获取config种的机器人配置
            $value = Cache::store('array')->remember("fsRobotWebHock:{$this->module}:{$this->projectName}", 60,
                function () {
                    return array_column(json_decode(ConfigModel::getValue($this->module, $this->projectName), true), null,
                        'value');
                });

            $robotConfig = $value[$this->robotValue] ?? null;

            // 没找到对应value的配置，通过tiger的基础飞书推送报警
            if (!$robotConfig) {
                Log::channel('fsRobot')->warning("NsqSubFsRobotCommand: 未找到机器人配置", $this->data);

                $title   = "NsqSubFsRobotCommand: 未找到机器人配置";
                $content = json_encode($this->data, JSON_UNESCAPED_UNICODE);
                SendFs::newRobot()
                      ->setTitleContent($title, $content)
                      ->setAtUid('9efgbcdb')
                      ->send();

                return;
            }

            $url   = $robotConfig['url'] ?? '';
            $token = $robotConfig['token'] ?? '';
        }

        // send
        $send = SendFs::newRobot()
                      ->coverConfig($url, $token)
                      ->setMessageBody($this->body)
                      ->send();

        Log::channel('fsRobot')->info("NsqSubFsRobotCommand Result: " . $send, $this->data);
        if (isTest()) {
            dump($send);
        }
    }

    private function app(): void
    {
        $send = MessageSendService::sendMessage($this->feishuId, 'user_id', $this->body, 'interactive',
            $this->robotValue);

        Log::channel('fsRobot')
           ->info("NsqSubFsRobotCommand Result: " . json_encode($send, JSON_UNESCAPED_UNICODE), $this->data);

        if (isTest()) {
            dump($send);
        }
    }
}
